package com.dearbinge.data.service.impl.address;

import com.dearbinge.data.api.address.AddressService;
import com.dearbinge.data.dao.address.RegionsMapper;
import com.dearbinge.data.dao.address.UserAddressMapper;
import com.dearbinge.data.pojo.address.Regions;
import com.dearbinge.data.pojo.address.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户地址
 *
 * @author wes
 * @date 2019/2/14
 */
@Service("addressService")
public class AddressServiceImpl implements AddressService {

    @Autowired
   private UserAddressMapper userAddressMapper;
    @Autowired
    private RegionsMapper regionsMapper;

    /**
     * 增加收货地址
     *
     * @param userAddress 地址
     * @return 结果
     */
    @Override
    public Integer insertAddress(UserAddress userAddress) {
        //新增的地址是否为默认地址
        Boolean defaultAddress = userAddress.getIsDefault();

        if (defaultAddress){
            //将旧的默认地址设置为非默认
            userAddressMapper.updateDefaultByUserId(userAddress.getUserId());
        }
        return  userAddressMapper.insert(userAddress);
    }

    /**
     * 修改收货地址
     *
     * @param userAddress 地址
     * @return 结果
     */
    @Override
    public Integer updateAddress(UserAddress userAddress) {
        //修改的地址是否为默认地址
        Boolean defaultAddress = userAddress.getIsDefault();
        if (defaultAddress){
            //将旧的默认地址设置为非默认
            userAddressMapper.updateDefaultByUserId(userAddress.getUserId());
        }
        return  userAddressMapper.update(userAddress);
    }

    /**
     * 删除地址
     *
     * @param id id
     * @return 结果
     */
    @Override
    public Integer deleteAddress(Integer id) {
        return userAddressMapper.deleteAddress(id);
    }

    /**
     * 根据id查询收藏地址
     *
     * @param id
     * @return
     */
    @Override
    public UserAddress getAddressById(Integer id) {
        return userAddressMapper.getUserAddressById(id);
    }

    /**
     * 根据用户id查询地址
     *
     * @param userId 用户id
     * @return 地址集
     */
    @Override
    public List<UserAddress> listAddressByUserId(String userId) {
        return userAddressMapper.listAddressByUserId(userId);
    }

    /**
     * 统计用户的地址数
     *
     * @param userId 用户id
     * @return 总数
     */
    @Override
    public Integer countAddressByUserId(String userId) {
        return userAddressMapper.countAddressByUserId(userId);
    }

    /**
     * 省市联动
     *
     * @param id 城市表
     * @return 结果集
     */
    @Override
    public List<Regions> listProvinceAndCity(String id) {
        return regionsMapper.listRegions(id);
    }
}
